package fun.zhufn.oldcomm.model.service;

import fun.zhufn.oldcomm.model.bo.Old;
import fun.zhufn.oldcomm.model.bo.customlist.OldList;
import fun.zhufn.oldcomm.model.dao.GlobalDataDao;

public class OldManagerService {
    private static final OldManagerService INSTANCE = new OldManagerService();
    private OldManagerService(){}

    public static OldManagerService getInstance(){return INSTANCE;}
    private static final GlobalDataDao dataDao = GlobalDataDao.getInstance();

    /**
     * @return 老人列表
     */
    public OldList getOldList() {
        var ret = new OldList();
        ret.fromJsonList(dataDao.getOldJsonList());
        return ret;
    }

    /**
     * @param ol 老人列表
     * @throws Exception 文件错误
     */
    public void setOldList(OldList ol) throws Exception {
        if (ol == null) return;
        dataDao.updateOldJsonList(ol.toJsonList());
        dataDao.saveToFile();
    }

    /**
     * @return 最大id
     */
    public int getMaxId() {
        int max = 0;
        for (var v: getOldList().getData()) {
            max = Math.max(max, v.getId());
        }
        return max;
    }

    /**
     * @param o 老人
     * @throws Exception 文件错误
     */
    public void addOld(Old o) throws Exception {
        if (o == null) return;
        o.setId(getMaxId() + 1);
        var ol = getOldList();
        var lo = ol.getData();
        lo.add(o);
        ol.setData(lo);
        setOldList(ol);
    }

    /**
     * @param o 老人
     * @throws Exception 文件错误
     */
    public void editOld(Old o) throws Exception {
        if (o == null) return;
        removeOld(o.getId());
        var ol = getOldList();
        var lo = ol.getData();
        lo.add(o);
        ol.setData(lo);
        setOldList(ol);
    }

    /**
     * @param x 老人id
     * @return 是否成功
     * @throws Exception 文件错误
     */
    public boolean removeOld(int x) throws Exception {
        var ol = getOldList();
        var lo = ol.getData();
        for (int i = 0; i < lo.size(); ++i) {
            if (lo.get(i).getId() == x) {
                lo.remove(i);
                ol.setData(lo);
                setOldList(ol);
                return true;
            }
        }
        return false;
    }

    /**
     * @param id 老人id
     * @param srv 服务人员账号
     * @throws Exception 文件错误
     */
    public void setOldSrv(int id, String srv) throws Exception {
        var ol = getOldList();
        var lo = ol.getData();
        for (int i = 0; i < lo.size(); ++i) {
            if (lo.get(i).getId() == id) {
                var t = lo.get(i);
                t.setServer(srv);
                lo.set(i, t);
                ol.setData(lo);
                setOldList(ol);
                dataDao.saveToFile();
                return;
            }
        }
    }
}
